package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/7/2 17:57
 * https://leetcode.cn/problems/palindrome-linked-list/
 */
public class Title234 {
    static class ListNode{
        int val;

        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }
    }

    public static boolean isPalindrome(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        //查找中间节点slow
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        //翻转slow.next之后的链表，并返回头结点
        slow = reverse(slow.next);
        while (slow != null) {
            if (slow.val != head.val) {
                return false;
            }
            slow = slow.next;
            head = head.next;
        }
        return true;
    }

    private static ListNode reverse(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode curNext = cur.next;
            cur.next = pre;
            pre = cur;
            cur = curNext;
        }
        return pre;
    }

    public static void main(String[] args) {
        ListNode list = new ListNode(1);
        list.next = new ListNode(2);
        isPalindrome(list);
    }
}
